package com.cskaoyan.realm;

import com.cskaoyan.bean.*;
import com.cskaoyan.mapper.MarketAdminMapper;
import com.cskaoyan.mapper.MarketPermissionMapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author hanshuai
 * @version 1.0
 * @description @TODO
 * @date 2021/12/2 9:07
 */
@Component
public class AdminRealm extends AuthorizingRealm {
    @Autowired
    MarketAdminMapper marketAdminMapper;
    @Autowired
    MarketPermissionMapper marketPermissionMapper;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        MarketAdminExample example = new MarketAdminExample();
        example.createCriteria().andUsernameEqualTo(username);
        List<MarketAdmin> marketAdmins = marketAdminMapper.selectByExample(example);
        String credential = marketAdmins.size() >= 1 ? marketAdmins.get(0).getUsername() : null;
        if (credential == null) {
            throw new AuthenticationException();
        }
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(username, credential, this.getName());
        return simpleAuthenticationInfo;

    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        String username = (String) principalCollection.getPrimaryPrincipal();
        MarketAdminExample example1 = new MarketAdminExample();
        example1.createCriteria().andUsernameEqualTo(username);
        List<MarketAdmin> marketAdmins = marketAdminMapper.selectByExample(example1);

        MarketPermissionExample example = new MarketPermissionExample();
        String[] split = marketAdmins.get(0).getRoleIds().replace("[", "").replace("]", "").split(",");
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        for (String s : split) {
            int i = Integer.parseInt(s);
            example.createCriteria().andRoleIdEqualTo(i);
            List<MarketPermission> marketPermissions = marketPermissionMapper.selectByExample(example);
            for (MarketPermission marketPermission : marketPermissions) {
                simpleAuthorizationInfo.addStringPermission(marketPermission.getPermission());
            }
        }
        return simpleAuthorizationInfo;
    }
}
